<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>规则管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" class="mg-top-20">
      <el-form-item label="类型">
        <el-radio-group
          v-model="formInline.type"
          size="medium"
          @change="getdata"
        >
          <el-radio-button label="scene">场景联动</el-radio-button>
          <el-radio-button label="flow">数据流转</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-plus"
          @click="handleAdd()"
          >添加</el-button
        >
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table
      size="small"
      :data="ruleList"
      highlight-current-row
      v-loading="$store.state.loading"
      border
      element-loading-text="拼命加载中"
      style="width: 100%"
    >
      <el-table-column align="center" type="selection" width="60">
      </el-table-column>
      <el-table-column sortable prop="name" label="规则名称" width="200">
      </el-table-column>
      <el-table-column sortable prop="createAt" label="创建时间" width="150">
        <template slot-scope="scope">
          <div>{{ scope.row.createAt | timestampToTime }}</div>
        </template>
      </el-table-column>
      <el-table-column
        prop="state"
        :formatter="stateFormat"
        label="状态"
        width="80"
      >
      </el-table-column>
      <el-table-column :formatter="stateFormat" label="执行日志" width="100">
        <template slot-scope="scope">
          <el-button plain @click="handleShowLog(scope.row)" size="mini"
            >查看</el-button
          >
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="250">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.$index, scope.row)"
            :disabled="scope.row.state == 'running'"
            >编辑</el-button
          >
          <el-button
            v-if="scope.row.state == 'running'"
            size="mini"
            type="danger"
            @click="handlePause(scope.$index, scope.row)"
            plain
            >停止</el-button
          >
          <el-button
            v-if="scope.row.state == 'stopped'"
            size="mini"
            type="success"
            @click="handleResume(scope.$index, scope.row)"
            plain
            >启动</el-button
          >
          <el-popconfirm
            title="确认要删除？"
            @confirm="handleDelete(scope.$index, scope.row)"
            class="mg-left-10"
          >
            <el-button
              slot="reference"
              size="mini"
              type="danger"
              :disabled="scope.row.state != 'stopped'"
              plain
              >删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination :data="formInline" @onPagePaging="getdata"></Pagination>

    <!-- 编辑界面 -->
    <el-dialog
      :title="title"
      :visible.sync="editFormVisible"
      width="80%"
      @click="closeDialog"
    >
      <el-form
        label-width="120px"
        :rules="rules"
        :model="editForm"
        ref="editForm"
      >
        <el-form-item label="规则名称" prop="name">
          <el-input
            size="small"
            v-model="editForm.name"
            auto-complete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="规则类型" prop="type">
          <el-select v-model="editForm.type">
            <el-option label="场景联动" value="scene"></el-option>
            <el-option label="数据流转" value="flow"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="监听器" prop="listeners">
          <el-card
            class="box-card"
            v-for="listener in editForm.listeners"
            :key="listener.id"
            :body-style="{ padding: '10px' }"
          >
            <el-row>
              <el-col :span="22"><Listener :data="listener"></Listener></el-col>
              <el-col :span="2"
                ><el-button
                  size="small"
                  type="error"
                  @click="delListener(listener)"
                  >删除</el-button
                ></el-col
              >
            </el-row>
          </el-card>
          <el-button size="small" @click="addListener()">新增</el-button>
        </el-form-item>
        <el-form-item label="过滤器" prop="filters">
          <el-card
            class="box-card"
            v-for="filter in editForm.filters"
            :key="filter.id"
            :body-style="{ padding: '10px' }"
          >
            <el-row>
              <el-col :span="22"><Filtera :data="filter"></Filtera></el-col>
              <el-col :span="2"
                ><el-button size="small" type="error" @click="delFilter(filter)"
                  >删除</el-button
                ></el-col
              >
            </el-row>
          </el-card>
          <el-button size="small" @click="addFilter()">新增</el-button>
        </el-form-item>
        <el-form-item label="输出" prop="actions">
          <el-card
            class="box-card"
            v-for="action in editForm.actions"
            :key="action.id"
            :body-style="{ padding: '10px' }"
          >
            <el-row>
              <el-col :span="22"
                ><Action :data="action" actions="device,http"></Action
              ></el-col>
              <el-col :span="2"
                ><el-button size="small" type="error" @click="delAction(action)"
                  >删除</el-button
                ></el-col
              >
            </el-row>
          </el-card>
          <el-button size="small" @click="addAction()">新增</el-button>
        </el-form-item>
        <el-form-item label="场景描述" prop="desc">
          <el-input
            size="small"
            v-model="editForm.desc"
            auto-complete="off"
            type="textarea"
            :rows="2"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button
          :disabled="editForm.state == 'running'"
          size="small"
          type="primary"
          :loading="$store.state.loading"
          class="title"
          @click="submitEditForm('editForm')"
          >保存</el-button
        >
      </div>
    </el-dialog>

    <el-dialog title="场景执行日志" :visible.sync="showLogVisible" width="60%">
      <RuleLogs :ruleId="ruleId"></RuleLogs>
    </el-dialog>
  </div>
</template>

<script>
import { uuid } from "../../utils/util.js";
import Pagination from "../../components/Pagination";
import Listener from "./Listener.vue";
import Filtera from "./Filter.vue";
import Action from "./Action.vue";
import RuleLogs from "./RuleLogs.vue";
import {
  RuleList,
  RuleSave,
  RuleDelete,
  RulePause,
  RuleResume,
} from "@/api/ruleApi.js";
export default {
  data() {
    var validateAction = (rule, value, callback) => {
      if (this.editForm.actions.length == 0) {
        callback(new Error("请设置输出"));
      } else {
        callback();
      }
    };
    return {
      loading: false, //是显示加载
      title: "",
      ruleList: [],
      formInline: {
        type: "scene",
        page: 1,
        size: 10,
        total: 0,
      },
      editForm: {
        name: "",
        type: "scene",
        state: "",
        listeners: [],
        filters: [],
        actions: [],
        desc: "",
      },
      rules: {
        name: [{ required: true, message: "请输入规则名称", trigger: "blur" }],
        actions: [{ validator: validateAction, trigger: "blur" }],
      },
      editFormVisible: false,
      showLogVisible: false,
      ruleId: "",
    };
  },
  components: {
    Pagination,
    Listener,
    Filtera,
    Action,
    RuleLogs,
  },
  created() {
    this.getdata();
  },
  methods: {
    getdata() {
      RuleList(this.formInline).then((rst) => {
        this.ruleList = rst.data;
        this.formInline.total = rst.total;
      });
    },
    stateFormat(row, column, value) {
      switch (value) {
        case "stopped":
          return "已停止";

        case "running":
          return "运行中";
      }
    },
    handleShowResult(result) {
      this.$alert(result, "执行结果", {
        confirmButtonText: "确定",
      });
    },
    handleAdd() {
      this.editFormVisible = true;
      this.title = "添加规则";
      this.editForm.id = "";
      this.editForm.type = "scene";
      this.editForm.state = "";
      this.editForm.name = "";
      this.editForm.listeners = [];
      this.editForm.filters = [];
      this.editForm.actions = [];
      this.editForm.desc = "";
    },
    handleEdit(index, row) {
      this.editFormVisible = true;
      this.title = "编辑规则";
      this.editForm.id = row.id;
      this.editForm.type = row.type;
      this.editForm.state = row.state;
      this.editForm.name = row.name;
      this.editForm.desc = row.desc;

      let listeners = [];
      row.listeners.forEach((a) => {
        listeners.push(JSON.parse(a.config));
      });
      this.editForm.listeners = listeners;

      let filters = [];
      row.filters.forEach((a) => {
        filters.push(JSON.parse(a.config));
      });
      this.editForm.filters = filters;

      let actions = [];
      row.actions.forEach((a) => {
        actions.push(JSON.parse(a.config));
      });
      this.editForm.actions = actions;
    },
    handlePause(index, row) {
      RulePause(row.id).then(() => {
        this.getdata();
      });
    },
    handleResume(index, row) {
      RuleResume(row.id).then(() => {
        this.getdata();
      });
    },
    handleDelete(index, row) {
      RuleDelete(row.id).then(() => {
        this.$notify({
          title: "成功",
          message: "删除成功",
          type: "success",
        });
        this.getdata();
      });
    },
    addListener() {
      this.editForm.listeners.push({
        id: uuid(),
        type: "device",
        topic: "",
        conditions: [],
      });
    },
    delListener(listener) {
      let idx = this.editForm.listeners.findIndex((l) => l.id == listener.id);
      this.editForm.listeners.splice(idx, 1);
    },
    addFilter() {
      this.editForm.filters.push({
        id: uuid(),
        type: "device",
        conditions: [],
      });
    },
    delFilter(filter) {
      let idx = this.editForm.filters.findIndex((o) => o.id == filter.id);
      this.editForm.filters.splice(idx, 1);
    },
    addAction() {
      this.editForm.actions.push({
        id: uuid(),
        type: "",
        services: [],
      });
    },
    delAction(action) {
      let idx = this.editForm.actions.findIndex((o) => o.id == action.id);
      this.editForm.actions.splice(idx, 1);
    },
    submitEditForm(from) {
      this.$refs[from].validate((valid) => {
        if (valid) {
          this.editForm.listeners.forEach((l) => {
            l.config = JSON.stringify(l);
          });
          this.editForm.filters.forEach((f) => {
            f.config = JSON.stringify(f);
          });
          this.editForm.actions.forEach((a) => {
            a.config = JSON.stringify(a);
          });

          RuleSave(this.editForm).then(() => {
            this.editFormVisible = false;
            this.$message({
              type: "success",
              message: "保存成功！",
            });
            this.getdata();
            this.editFormVisible = false;
          });
        }
      });
    },
    closeDialog() {
      this.editFormVisible = false;
    },
    handleShowLog(row) {
      this.ruleId = row.id;
      this.showLogVisible = true;
    },
  },
};
</script>